package com.littleken.core.validate;


import com.littleken.core.config.SecurityProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 图片code验证Filter
 */
@Slf4j
@Data
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    private AuthenticationFailureHandler authenticationFailureHandler;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    private Set<String> urls = new HashSet<>();//需要了拦截的url

    private SecurityProperties securityProperties;//配置类

    private AntPathMatcher antPathMatcher = new AntPathMatcher();//用于匹配带特殊符号 * 的字符串

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getImage().getUrl(),",");
        if (configUrls !=null){
            for(String configUrl : configUrls){
                urls.add(configUrl);
            }
        }
        urls.add("/authentication/form");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
       /* if(StringUtils.equals("/authentication/form",request.getRequestURI())
                && StringUtils.equalsIgnoreCase(request.getMethod(),"post")) {*/
       boolean action = false;
       for (String url : urls){
           if(antPathMatcher.match(url,request.getRequestURI())){
               action = true;
           }
       }

       if(action){
            try {
                validate(new ServletWebRequest(request));
            } catch (ValidateCodeException e) {//捕捉验证错误
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }

        chain.doFilter(request,response);

    }

    /**
     * 校验方法
     * @param request
     * @throws ValidateCodeException
     * @throws ServletRequestBindingException
     */
    private void validate(ServletWebRequest request) throws ServletRequestBindingException,ValidateCodeException{

        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"imageCode");//拿到用户输入的code

        ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request,ValidateCodeController.SESSION_KEY);//从session拿到code

        if(StringUtils.isBlank(codeInRequest)){//用户没输入验证码
            throw new ValidateCodeException("验证码不能为空");
        }

        if (codeInSession == null){//session中没有code
            throw new ValidateCodeException("验证码不存在");
        }

        if (codeInSession.isExpried()){
            sessionStrategy.removeAttribute(request,ValidateCodeController.SESSION_KEY);
            throw new ValidateCodeException("验证码过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(),codeInRequest)){
            throw new ValidateCodeException("验证码错误");
        }

        sessionStrategy.removeAttribute(request,ValidateCodeController.SESSION_KEY);
    }
}
